package com.sgcc.fj.pmos.mobileapp.presenter;

import android.text.TextUtils;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.sgcc.fj.pmos.common.base.BasePresenter;
import com.sgcc.fj.pmos.common.http.HttpInterConst;
import com.sgcc.fj.pmos.common.http.HttpRequestUtils;
import com.sgcc.fj.pmos.common.http.MvcNetCallback;
import com.sgcc.fj.pmos.common.http.MvpNetCallback;
import com.sgcc.fj.pmos.common.sm.SM3;
import com.sgcc.fj.pmos.common.utils.SignUtils;
import com.sgcc.fj.pmos.mobileapp.bean.CodeBean;
import com.sgcc.fj.pmos.mobileapp.bean.DoLoginReleaseBean;
import com.sgcc.fj.pmos.mobileapp.bean.LoginReleaseTokenBean;
import com.sgcc.fj.pmos.mobileapp.bean.MouldEditionBean;
import com.sgcc.fj.pmos.mobileapp.bean.RegisterBean;
import com.sgcc.fj.pmos.mobileapp.bean.SmsCodeBean;
import com.sgcc.fj.pmos.mobileapp.bean.VerifyExistMobileBean;
import com.sgcc.fj.pmos.mobileapp.contract.RegisteredContract;
import com.sgcc.fj.pmos.mobileapp.utils.SmUtils;
import com.sgcc.ln.pmos.common.interceptor.SignInterceptor;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class RegisteredPresenter extends BasePresenter<RegisteredContract.View> implements RegisteredContract.Presenter {

    @Override
    public void queryMouldEdition() {
        Map<String, Object> params = new HashMap<>();
        params.put("code", "GZFXS1");
        params.put("marketId", "PHBSX");
        params.put("membersType", 20);
        HttpRequestUtils.getInstance().request(params, HttpInterConst.QUERYMOULDEDITION, new MvpNetCallback<MouldEditionBean>(getView(), true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
                if (!isViewAttached()) {
                    return;
                }
            }

            @Override
            public void onResponse(MouldEditionBean response, int id) {
                super.onResponse(response, id);
                if (!isViewAttached()) {
                    return;
                }
                if (response != null) {
                    if (response.getStatus() == 0 && "Success".equals(response.getMessage())) {
                        getView().queryMouldEditionSuccess(response);
                    }
                }
            }
        });
    }

    @Override
    public void verifyExistMobile(String mobile) {
        Map<String, Object> params = new HashMap<>();
        params.put("appId", "618101657204559872");
        params.put("mobile", mobile);
        HttpRequestUtils.getInstance().request(params, HttpInterConst.VERIFYEXISTMOBILE, new MvpNetCallback<VerifyExistMobileBean>(getView(), true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
                if (!isViewAttached()) {
                    return;
                }
            }

            @Override
            public void onResponse(VerifyExistMobileBean response, int id) {
                super.onResponse(response, id);
                if (!isViewAttached()) {
                    return;
                }
                if (response != null) {
                    if (response.getStatus() == 0 && "Success".equals(response.getMessage())) {
                        getView().verifyExistMobileSuccess(response);
                    }
                }
            }
        });
    }

    @Override
    public void getSmsCode(String mobile) {
        Map<String, Object> params = new HashMap<>();
        params.put("smsType", 11);
        params.put("mobile", mobile);
        HttpRequestUtils.getInstance().request(params, HttpInterConst.GETSMSCODE, new MvpNetCallback<SmsCodeBean>(getView(), true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
                if (!isViewAttached()) {
                    return;
                }
            }

            @Override
            public void onResponse(SmsCodeBean response, int id) {
                super.onResponse(response, id);
                if (!isViewAttached()) {
                    return;
                }
                if (response != null) {
                    if (response.getStatus() == 0 && "Success".equals(response.getMessage())) {
                        getView().getSmsCodeSuccess(response);
                    } else {
                        ToastUtils.showShort(response.getMessage());
                    }
                }
            }
        });
    }

    @Override
    public void verifyExistLoginName(String loginName) {
        Map<String, Object> params = new HashMap<>();
        params.put("appId", "618101657204559872");
        params.put("loginName", loginName);
        HttpRequestUtils.getInstance().request(params, HttpInterConst.VERIFYEXISTLOGINNAME, new MvpNetCallback<VerifyExistMobileBean>(getView(), true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
                if (!isViewAttached()) {
                    return;
                }
            }

            @Override
            public void onResponse(VerifyExistMobileBean response, int id) {
                super.onResponse(response, id);
                if (!isViewAttached()) {
                    return;
                }
                if (response != null) {
                    if (response.getStatus() == 0 && "Success".equals(response.getMessage())) {
                        getView().verifyExistLoginNameSuccess(response);
                    }
                }
            }
        });
    }

    @Override
    public void startRegister(String loginName, String cipher, String mobile, String smsCode) {
        Map<String, Object> params = new HashMap<>();
        HttpRequestUtils.getInstance().request(params, HttpInterConst.REGISTER_GET_KEY, new MvpNetCallback<CodeBean>(getView(), true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
            }

            @Override
            public void onResponse(CodeBean response, int id) {
                super.onResponse(response, id);
                if (response != null && response.getStatus() == 0) {
                    try {
                        register(response.getData().getSecureCode(), response.getData().getSecureKey(), loginName, cipher, mobile, smsCode);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void register(String secureCode, String secureKey, String loginName, String cipher, String mobile, String smsCode) {
        Map<String, Object> params = new HashMap<>();
        String cipher_str = SmUtils.encryptSM2(cipher, secureKey);

        params.put("memberType", "20");
        params.put("appId", "618101657204559872");
        params.put("loginName", loginName);
        params.put("authKey", cipher_str);
        params.put("secureCode", secureCode);
        params.put("mobile", mobile);
        params.put("smsCode", smsCode);
        params.put("marketId", "PHBSX");

        HttpRequestUtils.getInstance().request(params, HttpInterConst.REGISTER, new MvpNetCallback<RegisterBean>(getView(), true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
                if (!isViewAttached()) {
                    return;
                }
            }

            @Override
            public void onResponse(RegisterBean response, int id) {
                super.onResponse(response, id);
                if (!isViewAttached()) {
                    return;
                }

                if (response != null) {
                    if (response.getStatus() == 0 && "Success".equals(response.getMessage())) {
                        if (!TextUtils.isEmpty(response.getData())) {
//                            SignInterceptor.Authorization = String.format("X-Ticket=%s; Admin-Token20090=%s", response.getData(), response.getData());
                            startLogin(loginName, cipher);
                        }
                    } else {
                        if (!TextUtils.isEmpty(response.getMessage())) {
                            ToastUtils.showShort(response.getMessage());
                        }
                    }
                }
            }

        });
    }


    public void startLogin(String username, String password) {
        Map<String, Object> params = new HashMap<>();
        HttpRequestUtils.getInstance().request(params, HttpInterConst.LOGIN_GET_KEY, new MvcNetCallback<CodeBean>(true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
                getView().registerFailed();
            }

            @Override
            public void onResponse(CodeBean response, int id) {
                super.onResponse(response, id);
                if (response != null && response.getStatus() == 0) {
                    try {
//                        if (HttpInterConst.isRelease) {
                        doLoginRelease(response.getData().getSecureCode(), response.getData().getSecureKey(), username, password);
//                        } else {
//                            doLogin(response.getData().getSecureCode(), response.getData().getSecureKey(), username, password);
//                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public void doLoginRelease(String secureCode, String secureKey, String username, String password) throws Exception {
        Map<String, Object> params = new HashMap<>();
        long currentTimeMillis = System.currentTimeMillis();
        String credential = SmUtils.encryptSM2(password, secureKey);

        SM3 sm3Dpct = new SM3();
        Map map = new HashMap();
        map.put("identifier", username);
        map.put("credential", credential);
        map.put("identityType", "UN");
        map.put("ot", currentTimeMillis);
        map.put("appId", "618101657204559872");
        map.put("secureCode", secureCode);
        String data = SignUtils.sortParams(map);
        String key = sm3Dpct.SM3Digest(data);

        params.put("secretKey", key);
        params.put("identifier", username);
        params.put("credential", credential);
        params.put("identityType", "UN");
        params.put("ot", currentTimeMillis);
        params.put("secureCode", secureCode);
        params.put("appId", "618101657204559872");

        HttpRequestUtils.getInstance().request(params, HttpInterConst.LOGIN_RELEASE, new MvpNetCallback<String>(getView(), true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                // 失败回调 判断界面是否销毁
                if (!isViewAttached()) {
                    return;
                }

                getView().registerFailed();
//                getView().();注册失败
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                if (!isViewAttached()) {
                    return;
                }
                DoLoginReleaseBean baseResponse = GsonUtils.fromJson(response, DoLoginReleaseBean.class);
                if (baseResponse != null) {
                    if (baseResponse.getStatus() == 0) {
                        LoginReleaseTokenBean loginReleaseTokenBean = GsonUtils.fromJson(response, LoginReleaseTokenBean.class);
                        if (loginReleaseTokenBean.getData() != null) {
                            if (loginReleaseTokenBean.getData().getAppToken() != null) {
                                SignInterceptor.Authorization = String.format("X-Ticket=%s; Admin-Token20090=%s", loginReleaseTokenBean.getData().getAppToken().getToken(), loginReleaseTokenBean.getData().getAppToken().getToken());
                                getView().registerSuccess();
                            } else {
                                if (!TextUtils.isEmpty(loginReleaseTokenBean.getMessage())) {
                                    ToastUtils.showShort(loginReleaseTokenBean.getMessage());
                                }
                            }
                        }
                    } else {
                        if (!TextUtils.isEmpty(baseResponse.getMessage())) {
                            ToastUtils.showShort(baseResponse.getMessage());
                        }
                    }
                } else {
//                    getView().LoginFailed();
                }
            }

        });
    }


}
